import { Injectable } from '@nestjs/common';
const { MongoClient } = require('mongodb');
const { nanoid } = require('nanoid')
const CryptoJS = require("crypto-js");
const Redis = require("ioredis");

const redis_client1 = new Redis({
    port: 6379, // Redis port
    host: "127.0.0.1", // Redis host
    db: 1,
});

const key = "just4fun"
const salt = "0x0"
const user_level = "user"

@Injectable()
export class UsersService {

    mongoUrl: any = process.env.mongoUrl;
    db: any;
    constructor() {
        this.connect()
    }

    async connect() {
        this.db = await MongoClient.connect(this.mongoUrl, { useUnifiedTopology: true })
    }

    async findOne(email: string, password: string) {
        console.log(email, password)
        const dbo = this.db.db("forum");
        const whereStr = {
            "email": (email).toString()
        }
        const hashed = CryptoJS.HmacSHA256(password + salt, key).toString()
        const result = await dbo.collection("users").findOne(whereStr)
        if (result && result.password == hashed) {
            const user_data = {
                username: result.username,
                userId: result.userId,
                level: result.level
            }
            return {
                "status": 20000,
                "user_data": user_data
            }
        } else {
            return { "status": 40000, "info": JSON.stringify(result) }
        }
        // return { status: 20000, user_data: { username: "ok", userId: "1233123", level: "user" } }
    }

    async register(user_json) {
        const dbo = this.db.db("forum");
        user_json["register_date"] = new Date()
        user_json.password = CryptoJS.HmacSHA256(user_json.password + salt, key).toString()
        user_json["userId"] = nanoid(10)
        user_json["honor"] = 0
        user_json["info"] = {}
        user_json["level"] = user_level
        if (user_json.invite != "") {
            let invite = await redis_client1.hgetall(user_json.invite)
            if (invite.userId) {
                user_json["invite_user"] = invite.userId
            }
        }
        console.log(user_json)
        const result = await dbo.collection("users").insertOne(user_json)
        if (result.insertedCount) {
            return { "status": 20000, "userId": user_json.userId, "level": user_level }
        } else {
            return { "status": 40000, "info": JSON.stringify(result) }
        }
    }

    async genInvite(user) {
        for (let i = 0; i < 3; i++) {
            await redis_client1.hmset(nanoid(12), "userId", user.userId)
        }

    }
}
